/**
 * webView
 */
import 'package:flutter_benchu/utils/commonPkg.dart';

class WebViewPage extends StatefulWidget {
  WebViewPage(
      {
        this.url = 'https://flutter.cn',
        this.title = '',
        this.showRefresh = true
      }
  );

  final String url;                           //地址
  final String title;                         //标题
  final bool showRefresh;                     //右上角刷新按钮

  State<StatefulWidget> createState() {
    return WebViewPageState();
  }
}

class WebViewPageState extends State<WebViewPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin,LoadingMixin {
  WebViewController _controller; //webview 控制器
  bool open = true; //是否渲染 webview
  String title = ''; //标题

  @override
  void initState() {
    super.initState();
    setState(() {isLoading = true;});
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;

   // 刷新按钮
  Widget getReloadIcon(BuildContext context) {
    if(!widget.showRefresh) return Container();
    if(isLoading) return Padding(padding: EdgeInsets.only(right: 15.w),child: Loading(size: 20,));
    return IconButton(
      icon: Icon(Icons.refresh),
      onPressed: () {
        _controller.reload();
        setState(() {isLoading = true;});
      },
    );
  }

  Widget getAppBar(BuildContext context) {
    return AppBar(
      centerTitle: true,
      title: Text(widget.title.isNotEmpty ? widget.title : title),
      actions: <Widget>[getReloadIcon(context)],
    );
  }

  Widget getBody(BuildContext context) {
    if (!open) return Container(color: Colors.transparent);
    return WebView(
      initialUrl: widget.url,
      javascriptMode: JavascriptMode.unrestricted, //是否允许JS执行
      onWebViewCreated: (WebViewController controller) {
        //初始化完成调用
        _controller = controller;
      },
      onPageFinished: (String url) {
        //页面加载完成
        _controller.evaluateJavascript("document.title").then((result) {
          setState(() {
            title = result;
            isLoading = false;
          });
        });
      },
      javascriptChannels: <JavascriptChannel>[
        JavascriptChannel(
          name: "appMessageChannel",
          onMessageReceived: (JavascriptMessage message) {
            Map map = json.decode(message.message);
            giveWebViewFunc[map['type']](context,map);
            print("参数： ${message.message}");
          }
        ),
      ].toSet(),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: getAppBar(context),
      body: loadingProvider(getBody(context)),
    );
  }
}
